<template>
	<div>

		<!-- 商品状态筛选 -->
		<el-tabs v-model="formData.status" @tab-click="findGoodsList">
			<el-tab-pane v-for="(item, index) in statuses" :key="index" :label="item"></el-tab-pane>
		</el-tabs>
		<!-- 操作及搜索 -->
		<div class="action-center">
			<div class="action-wrap">
				<router-link to="/goods/detail">
					<el-button type="primary" size="small" icon="el-icon-plus">添加商品</el-button>
				</router-link>
				<el-button-group style="margin-left: 20px;">
					<el-button :type="selectedIds.length > 0 ? 'warning' : 'info'" size="small" @click="batchUpdateStatus(0)">批量上架</el-button>
					<el-button :type="selectedIds.length > 0 ? 'warning' : 'info'" size="small" @click="batchUpdateStatus(1)">批量下架</el-button>
				</el-button-group>
			</div>
			<div class="simple-search" v-if="!advancedSearch">
				<el-input size="small" v-model="formData.keyword" placeholder="输入商品名称" prefix-icon="el-icon-search" maxlength="10"
				 @keyup.enter.native="findGoodsList">
					<el-button slot="append" @click="findGoodsList">搜索</el-button>
				</el-input>
				<el-button size="small" type="success" style="margin-left: 20px;" @click="advancedSearch = true;">高级搜索</el-button>
			</div>
		</div>
		<!-- 高级搜索 -->
		<el-card class="advanced-search" v-if="advancedSearch">
			<div slot="header" class="header">
				<span>高级搜索</span>
				<el-button type="text" icon="el-icon-arrow-up" @click="advancedSearch = false;">收起</el-button>
			</div>
			<el-form class="form" inline size="mini" @keyup.enter.native="findGoodsList">
				<el-form-item label="名称">
					<el-input v-model="formData.keyword" placeholder="输入商品名称" prefix-icon="el-icon-search"></el-input>
				</el-form-item>
				<el-form-item label="类别">
					<el-cascader v-model="formData.categoryId" :props="categoryProps" placeholder="选择商品类别" clearable></el-cascader>
				</el-form-item>
				<el-form-item label="品牌">
					<el-select v-model="formData.brandId" clearable placeholder="选择商品品牌">
						<el-option v-for="(item, index) in brands" :key="index" :label="item.name" :value="item.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="排序">
					<el-select v-model="formData.sortMode" clearable placeholder="选择排序模式">
						<el-option v-for="(item, index) in sorts" :key="index" :label="item" :value="index"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" icon="el-icon-search" @click="findGoodsList">搜索</el-button>
					<el-button type="info" icon="el-icon-refresh-right" @click="resetForm">重置</el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<!-- 商品列表 -->
		<el-table v-loading="loading" :data="goodsList" @selection-change="selectionChange" @expand-change="expandChange">
			<el-table-column type="selection" width="55"></el-table-column>
			<el-table-column label="商品信息" width="340">
				<template slot-scope="scope">
					<div style="display: flex;">
						<el-image :src="scope.row.thumbUrl" fit="contain" style="height: 100px;width: 100px;"></el-image>
						<div class="goods-details">
							<div class="name">{{scope.row.name}}</div>
							<div>品牌：{{scope.row.brand}}</div>
							<div class="time">创建于：{{scope.row.createTime}}</div>
						</div>
					</div>
				</template>
			</el-table-column>
			<el-table-column prop="category" label="类别" align="center"></el-table-column>
			<el-table-column prop="totalSales" label="总销量" align="center" :formatter="row => (row.totalSales || 0) + row.unit"></el-table-column>
			<el-table-column label="状态" align="center" width="140">
				<template slot-scope="scope">
					<el-button :type="scope.row.status == 0 ? 'success' : 'danger'" size="mini" plain :title="'点击' + (scope.row.status == 0 ? '下架' : '上架')"
					 @click="updateStatus(scope.row)">
						{{scope.row.status == 0 ? '出售中' : '已停售'}}
					</el-button>
				</template>
			</el-table-column>
			<el-table-column prop="totalStock" label="总库存" align="center" :formatter="row => (row.totalStock || 0) + row.unit"></el-table-column>
			<el-table-column prop="minPrice" label="最低售价" align="center" :formatter="row => '￥' + row.price"></el-table-column>
			<el-table-column label="规格" type="expand">
				<template slot-scope="props">
					<el-table :data="props.row.skus || []" v-loading="skuLoading">
						<el-table-column type="index"></el-table-column>
						<el-table-column prop="name" label="规格"></el-table-column>
						<el-table-column prop="stock" label="库存" align="center"></el-table-column>
						<el-table-column label="售价" align="center" :formatter="row => '￥' + row.price"></el-table-column>
						<el-table-column label="原售价" align="center" :formatter="row => (row.originalPrice ? '￥' + row.originalPrice : '-')"></el-table-column>
						<el-table-column label="成本价" align="center" :formatter="row => (row.costPrice ? '￥' + row.costPrice : '-')"></el-table-column>
						<el-table-column label="销量" align="center" :formatter="row => row.sales || 0"></el-table-column>
					</el-table>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" fixed="right">
				<template slot-scope="scope">
					<el-button type="text" size="small" icon="el-icon-edit-outline" @click="editGoods(scope.row.id)">编辑</el-button>
					<el-button type="text" size="small" icon="el-icon-delete" @click="deleteGoods(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 分页条 -->
		<div class="pagination-wrap" v-show="totalSize > pageSize">
			<el-pagination hide-on-single-page background @size-change="pageSizeChange" @current-change="pageNumberChange"
			 :current-page="pageNumber" :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
			 :total="totalSize">
			</el-pagination>
		</div>

	</div>
</template>

<script>
	export default {
		data() {
			return {
				statuses: ['全部', '出售中', '已停售'],
				formData: {
					status: '0',
					keyword: '',
					categoryId: '',
					brandId: '',
					sortMode: 0
				},
				categoryProps: {
					lazy: true,
					expandTrigger: 'hover',
					lazyLoad: (node, resolve) => {
						this.$util.request('/category', {
							parentId: node.root ? 0 : node.value
						}, (res) => {
							res = res.map(e => {
								return {
									label: e.name,
									value: e.id,
									leaf: !node.root
								}
							});
							resolve(res);
						}, true);
					}
				},
				brands: [],
				sorts: ['创建时间', '销售数量', '库存数量 - 多到少', '库存数量 - 少到多', '商品价格 - 低到高', '商品价格 - 高到低'],
				advancedSearch: false,
				goodsList: [],
				loading: true,
				pageNumber: 1,
				pageSize: 10,
				totalSize: 0,
				selectedIds: [],
				skuLoading: false
			}
		},
		created() {
			this.findGoodsList();
			this.findBrands();
		},
		methods: {
			findGoodsList(isSwitchPage = false) {
				if (!isSwitchPage) this.pageNumber = 1;

				this.loading = true;
				this.$util.request('/goods', {
					status: this.formData.status - 1,
					keyword: this.formData.keyword,
					categoryId: this.formData.categoryId ? this.formData.categoryId[1] : '',
					brandId: this.formData.brandId,
					sortMode: this.formData.sortMode,
					pageNumber: this.pageNumber,
					pageSize: this.pageSize
				}, (res) => {
					this.loading = false;

					this.goodsList = res.list.map(e => {
						e.createTime = this.$util.formatTime(e.createTime);
						return e;
					});
					this.totalSize = res.totalRow;
				}, true);
			},
			findBrands() {
				this.$util.request('/brand', {}, (res) => {
					this.brands = res;
				}, true);
			},
			resetForm() {
				this.formData = {
					status: '0',
					keyword: '',
					categoryId: '',
					brandId: '',
					sortMode: 0
				};

				this.findGoodsList();
			},
			pageSizeChange(e) {
				this.pageSize = e;
				this.findGoodsList(true);
			},
			pageNumberChange(e) {
				this.pageNumber = e;
				this.findGoodsList(true);
			},
			updateStatus(item) {
				this.$util.requestWithConfirm(`确定${item.status == 0 ? '下架' : '上架'}【${item.name}】吗？`, '/goods/updateStatus', {
					id: item.id
				}).then(_ => {
					this.findGoodsList(true);
				});
			},
			editGoods(id) {
				const newWindow = window.open(`/goods/detail?id=${id}`);
				const timer = setInterval(() => {
					if (newWindow.closed) {
						clearInterval(timer);
						this.findGoodsList(true);
					}
				}, 1000);
			},
			deleteGoods(item) {
				this.$util.requestWithConfirm(`确定删除【${item.name}】吗？`, '/goods/delete', {
					id: item.id
				}).then(_ => {
					this.findGoodsList();
				});
			},
			selectionChange(e) {
				this.selectedIds = e.map(e => {
					return e.id;
				});
			},
			batchUpdateStatus(status) {
				if (this.selectedIds.length == 0) return this.$util.msg('请先选择商品');

				this.$util.requestWithConfirm(`确定${status == 1 ? '下架' : '上架'}已选的${this.selectedIds.length}种商品吗？`,
					'/goods/batchUpdateStatus', {
						ids: this.selectedIds.join(','),
						status
					}).then(_ => {
					this.findGoodsList(true);
				});
			},
			expandChange(e, expandedRows) {
				const index = expandedRows.findIndex(goods => goods.id == e.id);
				if (index == -1 || e.skus) return;

				this.skuLoading = true;
				this.$util.request('/sku/findSkus', {
					goodsId: e.id
				}, (res) => {
					this.skuLoading = false;
					e.skus = res.map(sku => {
						sku.name = JSON.parse(sku.goodsAttr).map(attr => {
							return attr.value;
						}).join(' ');
						return sku;
					});
				}, true);
			}
		}
	}
</script>

<style lang="scss">
	.action-center {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20px;

		.simple-search {
			display: flex;
		}
	}

	.advanced-search {
		font-size: 14px;
		margin-bottom: 20px;
		animation: show .5s forwards;

		@keyframes show {
			from {
				opacity: 0;
			}

			to {
				opacity: 1;
			}
		}

		.header {
			@extend %flex-align-center;
			justify-content: space-between;
			margin: -15px -10px;
		}

		.form {
			margin-bottom: -10px;
		}
	}

	.goods-details {
		line-height: 2;
		margin-left: 10px;

		.name {
			font-size: 16px;
			font-weight: bold;
		}

		.time {
			font-size: 13px;
		}
	}
</style>
